import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { getCarListAPI, addCarAPI, deleteCarAPI } from '@/apis/car'
import { userInfoStore } from './user'
// import router from '@/router';
import { ElMessage } from 'element-plus';
import 'element-plus/theme-chalk/el-message.css'

export const useCarStore = defineStore('car', () => {
    const userStore = userInfoStore()
    console.log('userStore', userStore);
    // 获取token
    const isLogin = computed(() => userStore.userInfo.userId)
    const cartList = ref([])
    const cartSelectList = ref([])
    //更新购物车数据
    const updateCarList = async () => {
        let res = await getCarListAPI(userStore.userInfo.userId)
        console.log('res: getCarListAPI 购物车', res);
        cartList.value = res.data.map(item => {
            return {
                ...item,
                count: item.count || 1,
            }
        })
        cartSelectList.value = []
        console.log('updateCarList: ', cartList.value);
    }
    //添加购物车
    const addCar = async (goods) => {
        console.log('goods: ', goods);
        const {
            productId,
            count
         } = goods
        if (isLogin.value) {
            //接口购物车
            const tjForm ={
                uid: userStore.userInfo.userId,
                pid: productId,
                count: count
            }
            let res = await addCarAPI(tjForm)
            // if (res.status === 200) {
            ElMessage({ type: 'success', message: '已加入购物车' })
            await updateCarList()
            // }
        } else {
            // router.push('/login')
            // ElMessage.warning("请登录再购买")
            //本地购物车
            ElMessage({ type: 'success', message: '已加入购物车' })
            let item = cartList.value.find((item) => item.productId === goods.productId)
            if (item) {
                item.count = goods.count + item.count
            } else {
                cartList.value.push({ ...goods, count: goods.count })
            }
        }


    }
    //删除购物车
    const deleteCarItem = async (cartId) => {
        console.log('cartId: 删除接口购物车', cartId);
        if (isLogin.value) {
            //删除接口购物车
            let res = await deleteCarAPI({ cartIds: cartId })
            console.log('res: 删除接口购物车', res);
            ElMessage({ type: 'success', message: '已移除该商品' })
            //删除本地购物车
            const idx = cartList.value.findIndex((item) => item.cartId === cartId)
            if (idx !== -1) {
                cartList.value.splice(idx, 1)
                console.log('cartList.value: 删除本地购物车 ', cartList.value);
            }
            updateCarList()
        } else {
            //删除本地购物车
            ElMessage({ type: 'success', message: '已移除该商品' })
            const idx = cartList.value.findIndex((item) => item.cartId === cartId)
            if (idx !== -1) {
                cartList.value.splice(idx, 1)
            }
        }

    }
    //清楚购物车本地数据
    const clearCar = () => {
        cartList.value = []
        cartSelectList.value = []
    }
// 清空已选中的商品（新增）
const clearSelectedItems = () => {
    cartList.value = cartList.value.filter(item => !item.selected)
    cartSelectList.value = []
}

    //总数量和总价格
    const allCount = computed(() => cartList.value.length || 0)
    console.log('allCount: 总数量和总价格 ', allCount.value);
    const allPrice = computed(() => cartList.value.reduce((a, c) => {
        return a + c?.productInfo?.products?.price
    }, 0))
    console.log('allPrice: 总数量和总价格 ', allPrice.value);
    // 已选择数量
    const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0))
    // 已选择商品价钱合计
    const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => {
        const price = c?.productInfo?.products?.price
        const count = c.count
        return a + (price*count)
    }, 0))

    //单选框
    const singleCheck = (cartId, selected) => {
        console.log('cartId, selected: ', cartId, selected);
        const item = cartList.value.find((item) => item?.cartId === cartId)
        if (item) {

            item.selected = selected
            if (selected) {
                if(cartSelectList.value.length == 0){
                    cartSelectList.value.push(item)
                }
                else {
                    item.selected = !selected
                    console.log('cartId, item.selected: ', cartId, item.selected);
                    ElMessage({ type: 'waring', message: '只能选择一件商品！' })
                }
            } else {

                const i = cartSelectList.value.findIndex((item) => item?.cartId === cartId)
                if (i !== -1) {
                    cartSelectList.value.splice(i, 1);
                }
            }
        }
        console.log('cartSelectList  ', cartSelectList.value);
    }
    // 全选功能action
    const allCheck = (selected) => {
        // 把cartList中的每一项的selected都设置为当前的全选框状态
        cartList.value.forEach(item => item.selected = selected)
        if (selected) {
            cartSelectList.value = cartList.value
        } else {
            cartSelectList.value = []
        }
        console.log('cartSelectList ', cartSelectList.value);
    }
    // 是否全选计算属性
    const isAll = computed(() => cartList.value.every((item) => item.selected))
    return {
        isLogin,
        cartList,
        cartSelectList,
        allCount,
        allPrice,
        isAll,
        selectedCount,
        selectedPrice,
        addCar,
        deleteCarItem,
        singleCheck,
        allCheck,
        clearCar,
        clearSelectedItems, // 新增
        updateCarList
    }

}, {
    persist: true
})
